package cn.zzqayy.steward.gateway.utils;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @description: jwt工具类
 * @author: zzqayy
 * @date: 2020/3/1 21:34
 */
@Component
public class JwtUtils {

    /**
     * 添加相应的参数
     */
    private static final String CLAIM_KEY_AUTHORITIES = "scope";

    @Value("${custom.jwt.secret}")
    private String secret;

    @Value("${custom.jwt.expiration}")
    private Long expiration;

    @Value("${custom.jwt.client-name}")
    private String clientName;

    /**
     * 定义加密规则
     */
    private final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;

    /**
     * 获取token
     *
     * @param userDetails
     * @return
     */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>(1);
        claims.put(CLAIM_KEY_AUTHORITIES, userDetails.getAuthorities());
        String token = generateToken(userDetails.getUsername(), claims, expiration);
        return token;
    }

    /**
     * 通过token拿到用户名
     *
     * @param token
     * @return
     */
    public String getUsernameFromToken(String token) {
        String username = getClaimsFromToken(token).getSubject();
        return username;
    }

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            JwtParser jwtParser = getJwtParser();
            claims = jwtParser
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            e.printStackTrace();
            claims = null;
        }
        return claims;
    }

    /**
     * 验证有效性
     *
     * @param token
     * @param userDetails
     * @return
     */
    public boolean validateToken(String token, UserDetails userDetails) {
        User user = (User) userDetails;
        String username = getUsernameFromToken(token);
        return (username.equals(user.getUsername()) && !isTokenExpired(token));
    }

    /**
     * 生成token
     *
     * @param subject
     * @param claims
     * @param expiration
     * @return
     */
    private String generateToken(String subject, Map<String, Object> claims, long expiration) {
        Date date = new Date();
        Date afterDate = new Date(System.currentTimeMillis() + expiration);
        String token = Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(date)
                .setExpiration(afterDate)
                .compressWith(CompressionCodecs.DEFLATE)
                .signWith(getSecretKey())
                .compact();
        return token;
    }

    /**
     * 验证时间是否过期
     *
     * @param token
     * @return
     */
    private Boolean isTokenExpired(String token) {
        Date expiration = getClaimsFromToken(token).getExpiration();
        return expiration.before(new Date());
    }

    /**
     * jwt解析器
     *
     * @return
     */
    private final JwtParser getJwtParser() {
        JwtParser jwtParser = Jwts.parserBuilder()
                .setSigningKey(getSecretKey())
                .build();
        return jwtParser;
    }

    /**
     * 获取Key
     *
     * @return
     */
    private SecretKey getSecretKey() {
        //SecretKey secretKey = Keys.secretKeyFor(signatureAlgorithm);
        SecretKey secretKey = new SecretKeySpec(DatatypeConverter.parseBase64Binary(secret), signatureAlgorithm.getJcaName());
        return secretKey;
    }

}
